#!/usr/bin/env python

import glob, os, sys
import argparse

from moin_rpc import MoinRPC


parser = argparse.ArgumentParser ( description='LiWE Wiki Docs' )
parser.add_argument ( 'path', metavar='path', type = str, help='Documentation basepath' )
parser.add_argument ( 'wiki_user', metavar='user', type = str, help='Wiki User' )
parser.add_argument ( 'wiki_pwd', metavar='pwd', type = str, help='Wiki User password' )
parser.add_argument ( 'wiki_url', metavar='url', type = str, help='Wiki RPC URL' )

args = parser.parse_args()

dest_path = os.path.join ( os.path.dirname ( os.path.realpath( __file__ ) ), "source" )

print "DEST: %s" % dest_path


os.chdir ( args.path )


#moin = MoinRPC ( args.wiki_url, args.wiki_user, args.wiki_pwd )

def extract_jsdoc ( fname ):
	doc = []
	in_doc = False

	for l in open ( fname ):
		c = l.strip ()
		if c == "/**":
			in_doc = True
			continue
		elif c == "**/":
			in_doc = False
			doc.append ( "\n" )
		
		if in_doc: doc.append ( l )
			
	return ''.join ( doc )

def extract_pydoc ( fname ):
	return ''

def extract_rst ( fname ):
	return open ( fname ).read ().strip ()

def build_files_list ():
	res = []
	for root, subFolders, files in os.walk ( "." ):
		for f in files:
			if "excanvas" in f: continue
			if "bluff-src" in f: continue
			if "_static" in root: continue
			if f.endswith ( ".comp.js" ): continue
			if f.endswith ( ".js" ) or f.endswith ( ".py" ):
				res.append ( ( root, f ) )

	return res

def save_doc ( txt, d, f ):
	#txt  = "{{{#!rst\n%s\n}}}" % txt
	
	f = f.replace ( ".js", "" ).replace ( ".py", "" ).replace ( ".rst", "" )
	page_name = os.path.join ( d [ 2 : ], f )

	# ADD: saving in the right filesystem
	page_name = os.path.join ( dest_path, page_name + ".txt" )

	# Create all dest directories
	try:
		os.makedirs ( os.path.dirname ( page_name ) )
	except:
		pass

	print "Saving: %s" % page_name
	open ( page_name, "w" ).write ( txt )
	#moin.put_page ( page_name, txt )

	


for d, f in build_files_list ():
	fname = os.path.join ( d, f )

	if "os3jslib/graph/" in fname: continue
	if "docs/build/" in fname: continue

	if fname.endswith ( ".js" ):
		doc = extract_jsdoc ( fname )
	elif fname.endswith ( ".py" ):
		doc = extract_pydoc ( fname )
	elif fname.endswith ( ".rst" ):
		doc = extract_rst ( fname )

	if doc and len ( doc.strip () ):
		save_doc ( doc, d, f )

